package handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;

public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        readRequest(msg);

        String sendMsg;
        String uri = msg.uri();

        if ("/".equals(uri)) {
            sendMsg = "<h3>Netty HTTP Server</h3><a>Welcome to lyh.com</a>";
        } else if ("/hi".equals(uri)) {
            sendMsg = "<h3>Netty HTTP Server</h3><a>Hello word</a>";
        } else if ("/love".equals(uri)) {
            sendMsg = "<h3>Netty HTTP Server</h3><a>I Like this</a>";
        } else {
            sendMsg = "<h3>Netty HTTP Server</h3><a>I was lost</a>";
        }
        writeResponse(ctx,sendMsg);
    }

    private void readRequest(FullHttpRequest msg){
        System.out.println("=======请求行=======");
        System.out.println(msg.method() + " " + msg.uri() + " " + msg.getProtocolVersion());
        System.out.println("=======请求头=======");
        for (String name : msg.headers().names()) {
            System.out.println(name + ":" + msg.headers().get(name));
        }
        System.out.println("=======消息体=======");
        System.out.println(msg.content().toString(Charset.defaultCharset()));
    }

    private void writeResponse(ChannelHandlerContext ctx,String msg){
        ByteBuf buf = Unpooled.copiedBuffer(msg, Charset.defaultCharset());
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH,msg.length());
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }
}
